#!/bin/sh

# Navigate to TypeScript library directory
cd "$(dirname "$0")/.." || exit 1

echo "🔍 Running pre-commit checks..."

# 1. Run format to auto-fix formatting issues
echo "📝 Formatting code..."
pnpm format || {
  echo "❌ Formatting failed. Please fix the issues and try again."
  exit 1
}

# 2. Run lint:fix to auto-fix linting issues
echo "🔧 Fixing lint issues..."
pnpm lint:fix || {
  echo "❌ Linting failed. Please fix the issues and try again."
  exit 1
}

# 3. Stage any changes made by format and lint:fix
git add -u

# 4. Check for changeset when TypeScript files are modified
echo "📦 Checking for changeset..."

# Get list of staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

# Check if any TypeScript/JavaScript files were changed
HAS_CODE_CHANGES=$(echo "$STAGED_FILES" | grep -E '\.(ts|tsx|js|jsx)$' || true)

if [ -n "$HAS_CODE_CHANGES" ]; then
  # Check if there's a changeset file (excluding README.md)
  CHANGESET_FILES=$(find .changeset -name '*.md' -not -name 'README.md' 2>/dev/null || true)
  
  if [ -z "$CHANGESET_FILES" ]; then
    echo ""
    echo "❌ No changeset found!"
    echo ""
    echo "TypeScript/JavaScript files were modified but no changeset was added."
    echo "Please create a changeset before committing:"
    echo ""
    echo "  pnpm changeset"
    echo ""
    echo "If this change doesn't require a changeset (docs, tests, internal changes),"
    echo "you can bypass this check with:"
    echo ""
    echo "  git commit --no-verify"
    echo ""
    exit 1
  else
    echo "✅ Changeset found"
  fi
else
  echo "ℹ️  No code changes detected, skipping changeset check"
fi

echo "✅ All pre-commit checks passed!"
